package com.xxl.job.executor.sjbank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.executor.sjbank.mapper.*;
import com.xxl.job.executor.sjbank.pojo.FiAmort;
import com.xxl.job.executor.sjbank.pojo.FiAmortDetail;
import com.xxl.job.executor.sjbank.pojo.FiCreditcases;
import com.xxl.job.executor.sjbank.service.FiAmortDetailService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @author tsu
 * @description 针对表【fi_amort_detail(协商分期明细表)】的数据库操作Service实现
 * @createDate 2024-04-23 18:22:47
 */
@Service
public class FiAmortDetailServiceImpl extends ServiceImpl<FiAmortDetailMapper, FiAmortDetail>
        implements FiAmortDetailService {

    @Resource
    FiAmortMapper fiAmortMapper;
    @Resource
    FiCreditcasesMapper fiCreditcasesMapper;
    @Resource
    FiStopcallMapper fiStopcallMapper;

    @Override
    public void checkAmort() {
        List<FiAmortDetail> list = list(new QueryWrapper<FiAmortDetail>()
                .eq("status", 0)
                .lt("paydate", LocalDateTime.now()));
        XxlJobHelper.log("XXL-JOB, checkAmort.查询" + list.size() + "条.");
        list.forEach(x -> {
            FiAmort fiAmort = fiAmortMapper.selectOne(new QueryWrapper<FiAmort>()
                    .eq("applynumber", x.getAmortid()));
            FiCreditcases fiCreditcases = fiCreditcasesMapper.selectOne(new QueryWrapper<FiCreditcases>()
                    .eq("creditcaseid", fiAmort.getFicaseid()));
            BigDecimal repay = null;
            if (x.getPernumber() > 2) {
                LocalDateTime stime = startTime(x.getPaydate(), "00:00:00");
                LocalDateTime etime = endTime(x.getPaydate(), "23:59:59");
                repay = getPayAmount(fiCreditcases.getCreditAcct(), convertToDate(stime), convertToDate(etime));

            } else if (x.getPernumber() == 1) {
                LocalDateTime stime = minusTime(x.getPaydate(), "00:00:00");
                LocalDateTime etime = endTime(x.getPaydate(), "23:59:59");
                repay = getPayAmount(fiCreditcases.getCreditAcct(), convertToDate(stime), convertToDate(etime));
            } else if (x.getPernumber() == 2) {
                FiAmortDetail fiAmortDetail = baseMapper.selectOne(new QueryWrapper<FiAmortDetail>().eq("amortid", x.getAmortid()).eq("pernumber", 1));
                LocalDateTime etime = endTime(x.getPaydate(), "23:59:59");
                repay = getPayAmount(fiCreditcases.getCreditAcct(), fiAmortDetail.getPaydate(), convertToDate(etime));
            }

            if (x.getAmount().compareTo(repay) <= 0) {
                x.setStatus(1);
                x.setRepayment(repay);
                x.setUpdt(new Date());
                updateById(x);
            } else {
                x.setStatus(3);
                x.setRepayment(repay);
                x.setUpdt(new Date());
                updateById(x);
            }
        });
        //回写在催案件repay
        CanwriteRepay();
    }

    private void CanwriteRepay() {
        List<FiCreditcases> list = fiCreditcasesMapper.selectList(new QueryWrapper<FiCreditcases>()
                .in("ccc", "Q", "S", "R"));
        XxlJobHelper.log("XXL-JOB, 在催案件查询" + list.size() + "条.");
        list.forEach(x -> {
            fiCreditcasesMapper.update(null, new UpdateWrapper<FiCreditcases>()
                    .lambda()
                    .eq(FiCreditcases::getCreditcaseid, x.getCreditcaseid())
                    .set(FiCreditcases::getRepay, getPayAmount(x.getCreditAcct(), x.getDistdt(), new Date()))
            );
        });
    }

    private static LocalDateTime startTime(Date date, String time) {
        // 将 Date 转换为 LocalDate
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 获取上个月的同一天并加1天
        //LocalDate adjustedDate = localDate.minusMonths(1).plusDays(1);
        LocalDate adjustedDate = localDate.minusMonths(1);

        // 将时间部分解析为小时、分钟和秒
        String[] timeParts = time.split(":");
        int hour = Integer.parseInt(timeParts[0]);
        int minute = Integer.parseInt(timeParts[1]);
        int second = Integer.parseInt(timeParts[2]);

        // 返回包含日期和时间的 LocalDateTime 对象
        return LocalDateTime.of(adjustedDate, LocalDateTime.of(2020, 1, 1, hour, minute, second).toLocalTime());
    }

    private static LocalDateTime endTime(Date date, String time) {
        // 将 Date 转换为 LocalDate
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 将时间部分解析为小时、分钟和秒
        String[] timeParts = time.split(":");
        int hour = Integer.parseInt(timeParts[0]);
        int minute = Integer.parseInt(timeParts[1]);
        int second = Integer.parseInt(timeParts[2]);

        // 返回包含日期和时间的 LocalDateTime 对象
        return LocalDateTime.of(localDate, LocalDateTime.of(2020, 1, 1, hour, minute, second).toLocalTime());
    }

    private static LocalDateTime minusTime(Date date, String time) {
        // 将 Date 转换为 LocalDate
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        LocalDate adjustedDate = localDate.minusDays(1);

        // 将时间部分解析为小时、分钟和秒
        String[] timeParts = time.split(":");
        int hour = Integer.parseInt(timeParts[0]);
        int minute = Integer.parseInt(timeParts[1]);
        int second = Integer.parseInt(timeParts[2]);

        // 返回包含日期和时间的 LocalDateTime 对象
        return LocalDateTime.of(adjustedDate, LocalDateTime.of(2020, 1, 1, hour, minute, second).toLocalTime());
    }

    private static Date convertToDate(LocalDateTime localDateTime) {
        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 使用 Date.from() 将 Instant 转换为 Date
        return Date.from(instant);
    }

    private BigDecimal getPayAmount(String acctno, Date distDt, Date toDt) {//取实际还款额
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //开始时间从分案次日凌晨开始，在函数里面计算
            String distdt = sdf.format(distDt);
            String recydt = sdf.format(toDt);
            XxlJobHelper.log("参数：{} -->> {} -->> {}", acctno, distdt, recydt);
            return fiStopcallMapper.getPayAmount(acctno, distdt, recydt);
        } catch (Exception e) {
            //e.printStackTrace();
            XxlJobHelper.log("getPayAmount, 错误日志：", e);
            return new BigDecimal(0.0);
        }
    }
}




